import { ipcMain } from 'electron';
import Store from 'electron-store';
const version = 1;
const store = new Store({
    name: 'v1'
});

ipcMain.on('electron-store-set', (event, key, val) => {
    store.set(`${key}_${version}`, val)
    event.returnValue = store.get(`${key}_${version}`)
})
ipcMain.on('electron-store-get', (event, key) => {
    event.returnValue = store.get(`${key}_${version}`)
})
ipcMain.on('electron-store-remove', (event, key) => {
    store.delete(`${key}_${version}`)
    event.returnValue = store.get(`${key}_${version}`)
})
ipcMain.on('electron-store-clear', event => {
    store.clear()
    event.returnValue = ''
});



const cache = {

    get(key: string) {
        const value = store.get(`${key}_${version}`) as string || '';
        try {
            const model = JSON.parse(value);
            const data = model.value || '{"value":null}';
            const obj = JSON.parse(data);
            return obj.value;
        } catch (e) {
            return '';
        }
    },

    set(key: string, val: any, expire: number = 0) {
        const data = JSON.stringify({
            value: val,
        });
        const model = JSON.stringify({
            value: data,
            expire: expire > 0 ? Date.now() + expire : expire
        });
        store.set(`${key}_${version}`, model);
        return this;
    }

}

export { cache };